package cn.wizzer.app.user.modules.service.impl;

import cn.wizzer.app.user.modules.models.GroupMember;
import cn.wizzer.app.user.modules.models.enums.MsgTypeEnum;
import cn.wizzer.app.user.modules.models.enums.OprTypeEnum;
import cn.wizzer.app.user.modules.models.vo.GroupMemberVo;
import cn.wizzer.app.user.modules.services.GroupLogService;
import cn.wizzer.app.user.modules.services.GroupMemberService;
import cn.wizzer.app.user.modules.services.UserService;
import cn.wizzer.framework.base.Result;
import cn.wizzer.framework.base.service.BaseServiceImpl;
import cn.wizzer.framework.base.service.CommonDBService;
import cn.wizzer.framework.page.Pagination;
import com.alibaba.dubbo.config.annotation.Service;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.Times;

import java.util.List;

@IocBean(args = {"refer:dao"})
@Service(interfaceClass = GroupMemberService.class)
public class GroupMemberServiceImpl extends BaseServiceImpl<GroupMember> implements GroupMemberService {
    public GroupMemberServiceImpl(Dao dao) {
        super(dao);
    }

    @Inject
    private GroupLogService groupLogService;
    @Inject
    private UserService userService;
    @Inject
    private CommonDBService dbService;

    /**
     * 添加群成员
     *
     * @param userId
     * @param groupId
     */
    @Aop(TransAop.READ_COMMITTED)
    @Override
    public void addMember(String userId, String groupId) {
        //查询群里以前是否存在该成员，若存在则修改伪删除状态，若不存在则新增
        GroupMember groupMember = this.fetch(Cnd.where("userId", "=", userId).and("groupId", "=", groupId));
        if (groupMember == null) {
            //添加群成员
            groupMember = new GroupMember();
            groupMember.setGroupId(groupId);
            groupMember.setUserId(userId);
            groupMember.setSort(1);
            this.insert(groupMember);
        } else {
            //修改伪删除状态
            this.update(Chain.make("delFlag", 0)
                    .add("opAt", Times.getTS()).add("ctAt", Times.getTS()), Cnd.where("id", "=", groupMember.getId()));
        }

        String content = "大家好，我是" + userService.fetch(userId).getNickName() + "!";
        groupLogService.groupSend(userId, groupId, content, MsgTypeEnum.TEXT, OprTypeEnum.ADDED, false);
    }

    /**
     * 移除群成员
     *
     * @param userId
     * @param groupId
     */
    @Override
    public void delMember(String userId, String delUserId, String groupId) {
        this.update(Chain.make("delFlag", 1), Cnd.where("groupId", "=", groupId).and("userId", "=", delUserId));

        //添加消息记录
        String content = "群主移除了 " + userService.fetch(delUserId).getNickName();
        groupLogService.groupSend(userId, groupId, content, MsgTypeEnum.TEXT, OprTypeEnum.REMOVED, true);
    }

    /**
     * 群成员列表
     *
     * @param groupId
     * @return
     */
    @Override
    public List<GroupMember> list(String userId, String groupId) {
        GroupMember groupMember = this.fetch(Cnd.where("groupId", "=", groupId).and("userId", "=", userId).and("delFlag", "=", 0));
        if (groupMember == null) {
            Result.breakWith("你不在该群里，无法查看");
        }
        Sql sql = Sqls.create("SELECT u.id as userId, u.nickName, u.userName, u.headPicture " +
                "FROM group_member gm " +
                "LEFT JOIN `user` u ON gm.userId = u.id " +
                "WHERE gm.groupId = @groupId " +
                "AND gm.delFlag = 0 " +
                "ORDER BY gm.sort");
        sql.setParam("groupId", groupId);
        return dbService.list(GroupMemberVo.class, sql.toString());
    }

    @Override
    public Pagination listPage(int pageNumber, int pageSize, String groupName, String userKeyword, String[] searchDate) {
        Sql sql = Sqls.create("SELECT i.groupName, u.nickName, u.userName, u.headPicture, gm.id, gm.ctAt, gm.userId " +
                "FROM group_member gm ");
        Sql countSql = Sqls.create("SELECT COUNT(1) FROM group_member gm ");
        Sql joinSql = Sqls.create("LEFT JOIN user u ON u.id = gm.userId " +
                "LEFT JOIN group_info i ON i.id = gm.groupId " +
                "$condition ");
        Cnd cnd = Cnd.where("gm.delFlag", "=", 0);
        if (Strings.isNotBlank(groupName)) {
            groupName = "%" + groupName + "%";
            cnd.and("i.groupName", "LIKE", groupName);
        }
        if (Strings.isNotBlank(userKeyword)) {
            userKeyword = "%" + userKeyword + "%";
            cnd.and(Cnd.exps("u.nickName", "LIKE", userKeyword)
                    .or("u.userName", "LIKE", userKeyword));
        }
        if (searchDate != null && searchDate.length > 0) {
            cnd.and("gm.ctAt", ">=", Times.d2TS(Times.D(searchDate[0])));
            cnd.and("gm.ctAt", "<=", Times.d2TS(Times.D(searchDate[1])));
        }
        joinSql.setCondition(cnd);
        sql.appendSourceSql(joinSql.toString());
        sql.appendSourceSql("ORDER BY gm.ctAt DESC");
        countSql.appendSourceSql(joinSql.toString());
        return dbService.listPage(GroupMemberVo.class, pageNumber, pageSize, sql.toString(), countSql.toString());
    }

    /**
     * 批量添加群成员
     *
     * @param userIds
     * @param groupId
     */
    @Aop(TransAop.READ_COMMITTED)
    @Override
    public void batchAdd(String[] userIds, String groupId) {
        for (String userId : userIds) {
            addMember(userId, groupId);
        }
    }
}
